package com.nic.view.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.nic.view.R;

/**
 * Created by Administrator on 2018/11/14.
 */

public class CircleTextView extends View {

    private Paint circlePaint, circleTextPaint;
    private float textHeight;
    private String text;
    private float radius;

    public CircleTextView(Context context) {
        this(context, null);
    }

    public CircleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleTextView);
        text = typedArray.getString(R.styleable.CircleTextView_setText);
        initView();
        typedArray.recycle();
    }

    private void initView() {
        circlePaint = new Paint();
        circleTextPaint = new Paint();
        circlePaint.setAntiAlias(true);
        circleTextPaint.setAntiAlias(true);
        circlePaint.setColor(ContextCompat.getColor(getContext(), R.color.gray_300));
        circleTextPaint.setColor(ContextCompat.getColor(getContext(), R.color.gray_500));
        circlePaint.setStyle(Paint.Style.FILL);
        circlePaint.setStrokeWidth(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 100, getResources().getDisplayMetrics()));
        circleTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 30, getResources().getDisplayMetrics()));
        circleTextPaint.setTextAlign(Paint.Align.CENTER);
        Paint.FontMetrics metrics = circleTextPaint.getFontMetrics();
        textHeight = metrics.bottom - metrics.top;
        radius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 100, getResources().getDisplayMetrics()) / 2;
    }

    public void setText(String text) {
        this.text = text;
        invalidate();
    }

    public String getText() {
        return text;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension((int) radius * 2, (int) radius * 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (text != null) {
            canvas.drawCircle(radius, radius, radius, circlePaint);
            canvas.drawText(text, radius, radius + textHeight / 4, circleTextPaint);
        }
    }
}
